<script setup>
import { ref, onMounted, computed } from 'vue'
import axios from "axios";
import { useRouter } from 'vue-router'
import { HomeFilled, Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from 'element-plus'

// 返回首页
const router = useRouter()
const backToHome = () => {
    router.push('/student/Homepage/PersonalHomepage')
}

// 笔记数据
const active_tab = ref('all');
const tabs = ref([
    { name: 'all', label: '全部笔记' }
]);
const notes = ref([]);
const loading = ref(false);

// 获取所有笔记
const fetchNotes = async () => {
    loading.value = true;
  try {
        // 从localStorage获取学生信息
        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}');
        const username = studentInfo.username || studentInfo.stu_id;

        if (!username) {
            ElMessage.error('用户未登录');
            return;
        }

        // 请求后端API获取笔记
        const response = await axios.get('/api/student/course/notes/', {
            params: { username }
        });

        // 将返回的笔记保存到notes中
        notes.value = response.data || [];

        // 提取所有课程作为标签
        const courses = {};
        notes.value.forEach(note => {
            if (note.course_name && !courses[note.course_name]) {
                courses[note.course_name] = true;
            }
        });

        // 更新标签
        tabs.value = [
            { name: 'all', label: '全部笔记' },
            ...Object.keys(courses).map(name => ({ name, label: name }))
        ];

        console.log('获取到笔记数据:', notes.value);
  } catch (error) {
        console.error('获取笔记失败:', error);
        ElMessage.error('获取笔记失败，请稍后重试');
    } finally {
        loading.value = false;
    }
};

// 按标签筛选笔记
const filteredNotes = computed(() => {
    if (active_tab.value === 'all') {
        return notes.value;
    }
    return notes.value.filter(note => note.course_name === active_tab.value);
});

// 编辑笔记
const editNote = (note) => {
    router.push({
        path: '/student/edit-note',
        query: { id: note.id }
    });
};

// 删除笔记
const deleteNote = async (note) => {
    try {
        await ElMessageBox.confirm('确定要删除这个笔记吗？', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        });

        const studentInfo = JSON.parse(localStorage.getItem('studentUserInfo') || '{}');
        const username = studentInfo.username || studentInfo.stu_id;

        await axios.delete(`/api/student/course/notes/${note.id}`, {
            params: { username }
        });

        ElMessage.success('笔记删除成功');
        fetchNotes(); // 重新加载笔记列表
    } catch (error) {
        if (error !== 'cancel') {
            console.error('删除笔记失败:', error);
            ElMessage.error('删除笔记失败，请稍后重试');
        }
    }
};

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return '';
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
};

// 组件挂载时获取数据
onMounted(() => {
    fetchNotes();
});

// 创建新笔记
const createNewNote = () => {
    router.push('/student/edit-note');
};

// 切换聊天窗口显示/隐藏
const toggleChat = () => {
    const container = document.getElementById('chatContainer');
    if (container.style.display === 'none' || container.style.display === '') {
        container.style.display = 'block';
    } else {
        container.style.display = 'none';
    }
}

</script>

<template>
    <div class="note-page">
    <el-header style="padding: 20px">
        <el-row>
            <el-col :span="2">
                    <el-icon size="30" color="black" class="clickable">
                    <HomeFilled @click="backToHome"/>
                </el-icon>
            </el-col>
            <el-col :span="20">
                <div style="text-align: center; font-size: large">
                        学习笔记
                </div>
            </el-col>
                <el-col :span="2">
                    <el-button type="primary" @click="createNewNote">
                        新建笔记
                    </el-button>
                </el-col>
        </el-row>
    </el-header>

    <el-main>
            <div class="notes-container">
            <el-tabs
                v-model="active_tab"
                type="border-card"
                tab-position="left"
                    style="height: 85vh; width: 100%"
                    v-loading="loading"
            >
                <el-tab-pane
                    v-for="tab in tabs"
                    :key="tab.name"
                    :label="tab.label"
                    :name="tab.name"
                >
                        <div v-if="filteredNotes.length === 0" class="empty-notes">
                            <el-empty description="暂无笔记" />
                        </div>

                        <div v-else class="notes-list">
                            <el-card v-for="note in filteredNotes" :key="note.id" class="note-card">
                                <template #header>
                                    <div class="note-header">
                                        <h3>{{ note.note_title || '无标题' }}</h3>
                                        <div class="note-actions">
                                            <el-button type="primary" text :icon="Edit" @click="editNote(note)">
                                                编辑
                                            </el-button>
                                            <el-button type="danger" text :icon="Delete" @click="deleteNote(note)">
                                                删除
                                            </el-button>
                                        </div>
                                    </div>
                                </template>

                                <div class="note-meta">
                                    <span>课程：{{ note.course_name || '未分类' }}</span>
                                    <span>创建时间：{{ formatDate(note.created_at) }}</span>
                                </div>

                        <div class="note-content">
                                    {{ note.note_content }}
                        </div>
                            </el-card>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </el-main>
    </div>
    <div class="chat-bubble" @click="toggleChat">
        <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='white'%3E%3Cpath d='M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z'/%3E%3C/svg%3E" alt="聊天">
    </div>

    <div class="chat-container" id="chatContainer">
        <iframe src="http://121.40.242.43/chatbot/c7ZSvPxvxyO1fuIo" class="chat-iframe"></iframe>
    </div>
</template>

<style scoped>
.note-page {
    display: flex;
    flex-direction: column;
    height: 100vh;
}

.notes-container {
    width: 100%;
    height: 100%;
}

.notes-list {
    display: flex;
    flex-direction: column;
    gap: 20px;
    padding: 10px;
}

.note-card {
    margin-bottom: 15px;
}

.note-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.note-actions {
    display: flex;
    gap: 10px;
}

.note-meta {
  color: #666;
  margin-bottom: 15px;
    display: flex;
    justify-content: space-between;
    font-size: 0.9em;
}

.note-content {
  white-space: pre-wrap;
  line-height: 1.6;
    max-height: 200px;
    overflow-y: auto;
    background: #f8f9fa;
    padding: 10px;
    border-radius: 4px;
}

.empty-notes {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
}

.clickable {
    cursor: pointer;
}
.chat-bubble {
    position: fixed;
    bottom: 20px;
    right: 20px;
    width: 60px;
    height: 60px;
    background-color: #007bff;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    z-index: 1000;
}

.chat-bubble img {
    width: 30px;
    height: 30px;
}

.chat-container {
    position: fixed;
    bottom: 100px;
    right: 20px;
    width: 350px;
    height: 500px;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    display: none;
    z-index: 999;
}

.chat-iframe {
    width: 100%;
    height: 100%;
    border: none;
    border-radius: 10px;
}
</style>
